/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.iec.edp.caf.logging.logback.appender;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.util.LevelToSyslogSeverity;
import ch.qos.logback.core.net.SyslogAppenderBase;

import java.net.SocketException;
import java.net.UnknownHostException;

/**
 * 支持UDP发送日志信息
 * @author wangyandong
 * @date 2021/06/18 14:21
 *
 */
public class CafSocketAppender
        extends CafSyslogAppenderBase<ILoggingEvent> {
    /**
     * 是否启用
     */
    private Boolean enabled=false;

    @Override
    public CafSyslogOutputStream createOutputStream() throws UnknownHostException, SocketException {
        return new CafSyslogOutputStream(getHost(), getPort());
    }

    @Override
    public void start() {
        //如果未启用,则直接不开始
        if(!this.isEnabled()){
            return;
        }
        super.start();
    }

    /**
     * Convert a level to equivalent syslog severity. Only levels for printing
     * methods i.e DEBUG, WARN, INFO and ERROR are converted.
     *
     * @see SyslogAppenderBase#getSeverityForEvent(Object)
     */
    @Override
    public int getSeverityForEvent(Object eventObject) {
        ILoggingEvent event = (ILoggingEvent) eventObject;
        return LevelToSyslogSeverity.convert(event);
    }

    /**
     * 返回启用状态
     * @return
     */
    public Boolean isEnabled(){
        return this.enabled;
    }

    /**
     * 设置appender是否启用
     * @param enabled
     */
    public void setEnabled(Boolean enabled){
        this.enabled = enabled;
    }
}
